
from collections import deque
import time
import threading
import chiasynclib
import os

global g_cmdQStack;

def exec_mv_plots(arg):
    print ("exec_mv_plots")
    while True:
        if len(g_cmdQStack) != 0:
            cmd = g_cmdQStack.popleft()
            print ("deque:" + cmd)
            os.system(cmd)
        else:
            time.sleep(1)

def exec_enqueue_mv_cmd(arg):
    print ("exec_enqueue_mv_cmd")

    fpipe = open('/tmp/chiasyncpi', 'r')

    while True:
        line = chiasynclib.pipe_read(fpipe)
        '''check'''
        if line != "":
            print("enqueue:" + line)
            g_cmdQStack.append(line)
        else:
            print("enqueue line is empty")
        time.sleep(1)

if __name__ == '__main__':
    ''' clear the name pipe'''
    chiasynclib.pipe_destory()
    chiasynclib.pipe_create()
    g_cmdQStack = deque()

    #g_cmdQStack.append(1)
    #g_cmdQStack.append(2)
    #g_cmdQStack.append("hello world")
    #print (list(g_cmdQStack))

    if len(g_cmdQStack) == 0:
        print ("queue is empty")
    else:
        print (g_cmdQStack.popleft())
    if len(g_cmdQStack) == 0:
        print ("queue is empty")
    else:
        print(list(g_cmdQStack))

    t1 = time.time()
    os.system("sleep 1")
    t2 = time.time()
    print (t2 - t1)

    print ("started two threads")
    thread_enque = threading.Thread(target=exec_enqueue_mv_cmd, args=(0,))
    thread_execmd = threading.Thread(target=exec_mv_plots, args=(0,))

    thread_enque.start()
    thread_execmd.start()

    thread_execmd.join()
    thread_execmd.join()
